class ContractsController < ApplicationController
  protect_from_forgery :only => [:create, :destroy, :update]

  def index
    if params[:client_id]
      @contracts = Contract.find(:all, :conditions => ["client_id = ?", params[:client_id]]).paginate :per_page => 10, :page => params[:page]
    else
      @contracts = Contract.find(:all).paginate :per_page => 10, :page => params[:page]
    end

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @contracts }
    end
  end

  def show
    @contract = Contract.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @contract }
    end
  end
  
  def expired
    @contracts = Contract.find(:all, 
                               :conditions => ['expiration <= ?', Date.today + 3.months] ).paginate :per_page => 10, 
                               :page => params[:page]

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @contract }
    end
  end

  def new
    @contract = Contract.new
    if params[:id]
      @contract.client_id = params[:id]
    end
    
    respond_to do |format|
      if params[:id]
        format.html # new.html.erb
        format.xml  { render :xml => @contract }
      else
        flash[:alert] = 'Non è possibile creare un Contratto se non associato ad un cliente.'
        format.html {redirect_to clients_path}
      end
    end
  end

  def edit
    @contract = Contract.find(params[:id])
  end

  def create
    @contract = Contract.new(params[:contract])

    respond_to do |format|
      if @contract.save
        flash[:notice] = 'Contratto creato con successo.'
        format.html { redirect_to(@contract) }
        format.xml  { render :xml => @contract, :status => :created, :location => @contract }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @contract.errors, :status => :unprocessable_entity }
      end
    end
  end

  def update
    params[:contract][:service_ids] ||= []
    @contract = Contract.find(params[:id])

    respond_to do |format|
      if @contract.update_attributes(params[:contract])
        flash[:notice] = 'Contratto aggiornato con successo.'
        format.html { redirect_to(@contract) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @contract.errors, :status => :unprocessable_entity }
      end
    end
  end

  def destroy
    @contract = Contract.find(params[:id])
    @contract.destroy

    respond_to do |format|
      format.html { redirect_to(contracts_url) }
      format.xml  { head :ok }
    end
  end
end
